package com.joint.web.action.mp;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.entity.Comment;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.parent.NameEntity;
import com.joint.base.service.CommentService;
import com.joint.base.service.CompanyService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.Client;
import com.joint.core.entity.ProBack;
import com.joint.core.entity.ProSignIn;
import com.joint.core.service.ClientService;
import com.joint.core.service.ProBackService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseController;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台Action类 - 批注信息列表
 * ============================================================================
 * 版权所有 2014 min_xu。
 * ----------------------------------------------------------------------------
 *
 * @author min_xu
 *
 * @version 0.1 2014-4-11
 */
@Controller("mpComment")
@RequestMapping("/mp")
public class AjaxCommentController extends BaseController {
    private static final long serialVersionUID = -5383463207248344967L;



    @Resource
    private UsersService usersService;
    @Resource
    private CompanyService companyService;
    @Resource
    private ClientService clientService;
    @Resource
    private CommentService commentService;
    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ProBackService proBackService;

    private Users users;
    private String name;
    private String type;
    private Client client;
    /**
     * 批注相关
     * **/
    private Comment comment;
    private String targetId;
    private String toUsersId;
    private String parentId;
    private String targetObject;
    private String text;
    private String clickId;
    private String searchString;

    private String checkText;

    private String query;

    private List<Comment> listComm;

    private List<Map<String,Object>> toUserList;
    private List<Map<String,Object>> usersListpage;
    private List<Map<String,Object>> listmapComm;
    private Map<String,List<Map<String,Object>>> userListMap;

    public String usersPage(){
        Pager upager = new Pager(0);
        upager.setOrderBy("pinYinHead");
        Map<String,Object> map=Maps.newHashMap();
        map.put("state", BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(searchString)){
            map.put("name",searchString);
        }

        upager.setOrderType(BaseEnum.OrderType.asc);
        List<Users> usersList = (List<Users>) usersService.findByPagerAndCompany(upager, null,usersService.getCompanyByUser(),map).getList();
        usersListpage=Lists.newArrayList();
        userListMap=Maps.newLinkedHashMap();
        for(Users users : usersList){
            Map<String,Object> rmap=Maps.newHashMap();
            List<Map<String,Object>> tmplist = null;
            String pinyinHead = users.getPinYinHead();
            String headstr = "";
            rmap=Maps.newHashMap();
            if(pinyinHead != null){
                headstr = com.joint.base.util.StringUtils.upperCase(String.valueOf(pinyinHead.charAt(0)));
            }
            if(userListMap.containsKey(headstr)){
                tmplist=userListMap.get(headstr);
                rmap.put("id",users.getId());
                rmap.put("name",users.getName());
                tmplist.add(rmap);
            }else{
                tmplist=Lists.newArrayList();
                rmap.put("id",users.getId());
                rmap.put("name",users.getName());
                tmplist.add(rmap);
            }
            userListMap.put(headstr,tmplist);
        }
        return "usersPage";
    }

    public String view(){
        return "view";
    }

    // 一览
    public String list() {
        Company company = usersService.getCompanyByUser();
        Map<String,Object> rmap=Maps.newHashMap();
        pager=new Pager(0);
        if(company == null){
            return "error_timeout";
        }
        //keyId = "3426359a453ce6050145406f76b3003e";
        if (StringUtils.isEmpty(keyId) == true) {

        }else{
            rmap.put("targetId",keyId);
            pager=commentService.findByPagerAndLimit(pager,users,company,rmap);
//			for(Comment comment1:listComm){
//				//comment1.setCreateDateText(DataUtil.friendly_time(comment1.getCreateDate()));
//				comment1.setFacedText(FaceUtil.getWebFacedText(comment1.getText()));
//			}
        }
        return "list";
    }

    public String listDocument() {
        Company company = usersService.getCompanyByUser();
        Users users=usersService.getLoginInfo();
        Map<String,Object> rmap=Maps.newHashMap();
        if(users!=null){
            if (StringUtils.isEmpty(keyId) == true) {

            }else{
                pager = new Pager(0);
                rmap.put("targetId",keyId);
                pager=commentService.findByPagerAndLimit(pager,users,company,rmap);
                List<Comment> commentList= (List<Comment>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
                Map<String,Object>  umap=null;
                listmapComm=Lists.newArrayList();
                for(Comment comment:commentList) {
                    String names="";
                    umap = Maps.newHashMap();
                    umap.put("id", comment.getId());
                    umap.put("createUser", comment.getCreater().getName());
                    umap.put("userId", comment.getCreater().getId());
                    umap.put("headImage", "");
                    umap.put("createDate", comment.getCreateDate());
                    umap.put("model", comment.getModel());
                    umap.put("text", comment.getText());
                    if (StringUtils.isNotEmpty(comment.getAtUsers())) {
                        for (String s : comment.getAtUsers().split(",")) {
                            users = usersService.get(s);
                            names += "@" + users.getName() + ",";
                        }
                    }
                    umap.put("atUsers",names.length()>0?names.substring(0,names.length()-1):"");
                    listmapComm.add(umap);
                }
            }
        }
        return "listDocument";
    }

    //
    public String save() {
        Users creater = usersService.getLoginInfo();
        Company company=usersService.getCompanyByUser();
        Set<Users> usersSet= Sets.newHashSet();
        String content="";
        String atUsers="";
        Map<String,Object> rmap=Maps.newHashMap();
        rmap.put("state", BaseEnum.StateEnum.Enable);
        pager=usersService.findByPagerAndCompany(new Pager(0),null,company,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<Users> usersList= (List<Users>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
        if (StringUtils.isEmpty(targetId)) {
            return ajaxHtmlCallback("400", "获取批注对象失败！", "操作状态");
        }
        if (StringUtils.isEmpty(text)) {
            return ajaxHtmlCallback("400", "批注信息不允许为空！", "操作状态");
        }
        if(StringUtils.isEmpty(toUsersId)){
            switch (targetObject){
                case "com.joint.core.entity.ProInfo":
                    usersSet.add(proInfoService.get(targetId).getChief());
                    usersSet.addAll(proInfoService.get(targetId).getGroup());
                    break;
                case "com.joint.core.entity.ProBack":
                    usersSet.add(proBackService.get(targetId).getProInfo().getChief());
                    usersSet.addAll(proBackService.get(targetId).getProInfo().getGroup());
                    break;
                default:
                    usersSet.addAll(usersList);
            }
        }else{
            atUsers+=toUsersId;
            for(String id:toUsersId.split(",")){
                usersSet.add(usersService.get(id));
            }
        }

        Comment comment = new Comment(creater,targetId,targetObject,null, EnumManage.CommentModelEnum.text,text,atUsers);
        comment.setCompany(creater.getCompany());
        if(usersSet.size()>0){
            commentService.createNewCommentApp(comment, usersSet);
        }


        return ajaxHtmlCallback("200",  "批注成功!","操作状态");
    }

    //查看评论判断是否是当前登陆人
    public boolean isCurrentUser(String id){
        Users currentUser=usersService.getLoginInfo();
        if(StringUtils.equals(currentUser.getId(),id)){
            return true;
        }else{
            return false;
        }
    }
    public String feedbackCheck(){
        comment = commentService.get(keyId);
        //comment.setCommentState(CommentState.)
        //comment.setType(CommentTypeEnum.important);
        comment.setIfFeedbackChecked(1);
        comment.setCheckText(checkText);
        commentService.update(comment);
        return ajaxHtmlCallback("200", "需求确认成功。", "");
    }
    //@我的批注列表
    @RequestMapping(value = "/ajax-comment/toUsersList",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> toUsersList(int page,String pageKeyword){
        users = usersService.getLoginInfo();
        Company company = usersService.getCompanyByUser();
        Map<String, Object> map;
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Pager pager = new Pager();
        pager.setPageSize(10);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        pager.setPageNumber(page);
        toUserList = Lists.newArrayList();
        List<Comment> comments = Lists.newArrayList();

        pager = commentService.getPager(pager, users, null, "", "", -1, -1, null, null, BaseEnum.StateEnum.Enable);
        comments= pager.getTotalCount()>0? (List<Comment>) pager.getList() :comments;

        for(Comment c : comments){
            String names="";
            map = commentService.getListMap(c);
            Object obj = commentService.getObject(c.getTargetClass(), c.getTargetId());
            String clazz = StringUtils.substringAfterLast(c.getTargetClass(),".");
            //map.put("uriName","ajax-"+StringUtils.lowerCase(clazz));

            if(obj instanceof NameEntity){
                NameEntity nObj = (NameEntity) obj;
                map.put("theme",nObj.getName()+"中进行反馈");
            }
            if(obj instanceof ProBack){
                ProBack proBack = (ProBack) obj;
                map.put("theme",proBack.getProInfo().getName()+"中进行反馈");
            }
            if(obj instanceof ProSignIn){
                ProSignIn proSignIn = (ProSignIn) obj;
                map.put("theme",proSignIn.getProInfo().getName()+"中进行签到");
            }
            if(StringUtils.isNotEmpty(c.getAtUsers())){
                for(String s:c.getAtUsers().split(",")){
                    names+="@"+usersService.get(s).getName()+",";
                }
            }
            map.put("model",c.getModel());
            map.put("text",c.getText());
            map.put("creater",c.getCreater().getName());
            map.put("atUsers",names.length()>0?names.substring(0,names.length()-1):"");
            map.put("url",getPath()+"mp/ajax-"+StringUtils.lowerCase(clazz)+"/read/"+c.getTargetId());
            map.put("createDate", DateFormatUtils.format(c.getCreateDate(),"yyyy-MM-dd"));
            dataRows.add(JSONObject.fromObject(map));
        }

        data.put("pageNum", pager.getPageNumber());//页数
        data.put("pageSize", dataRows.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("pageKeyword", pager.getKeyword()==null?"": pager.getKeyword());//查询
        data.put("dataRows", dataRows);//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    //我批注的列表
    public String createrList(){
        users = usersService.getLoginInfo();
        pager = new Pager();
        pager.setPageNumber(1);// 页码
        pager.setPageSize(100);// 页Size
        pager.setOrderType(BaseEnum.OrderType.desc);
        pager.setOrderBy("createDate");
        pager = commentService.getPager(pager, users, null, null, null, -1, -1, null, null,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});

        List<Comment> comments = (List<Comment>) pager.getList();
        listComm = new ArrayList<Comment>();
        for(Comment c : comments){
            if(c.getTargetId() != null){
//				Map<String,String> map = commentService.getTargetMap(c);
//				c.setSubject(map.get("subject"));
//				c.setClientName(map.get("clientName"));
//				c.setUriName(map.get("type"));
//				listComm.add(c);
            }
        }
        return "createrList";
    }
    private Set<Users> getUserSpit(String str){
        Set<Users> usersSet=new HashSet<Users>();
        String[] ary=str.split(",");
        for(String item:ary){
            if(StringUtils.isNotEmpty(item)){
                usersSet.add(usersService.get(item));
            }
        }
        return  usersSet;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    public List<Comment> getListComm() {
        return listComm;
    }

    public void setListComm(List<Comment> listComm) {
        this.listComm = listComm;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public String getTargetId() {
        return targetId;
    }

    public void setTargetId(String targetId) {
        this.targetId = targetId;
    }

    public String getToUsersId() {
        return toUsersId;
    }

    public void setToUsersId(String toUsersId) {
        this.toUsersId = toUsersId;
    }

    public String getTargetObject() {
        return targetObject;
    }

    public void setTargetObject(String targetObject) {
        this.targetObject = targetObject;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getClickId() {
        return clickId;
    }

    public void setClickId(String clickId) {
        this.clickId = clickId;
    }

    public String getCheckText() {
        return checkText;
    }

    public void setCheckText(String checkText) {
        this.checkText = checkText;
    }

    public List<Map<String, Object>> getToUserList() {
        return toUserList;
    }

    public void setToUserList(List<Map<String, Object>> toUserList) {
        this.toUserList = toUserList;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public List<Map<String, Object>> getUsersListpage() {
        return usersListpage;
    }

    public void setUsersListpage(List<Map<String, Object>> usersListpage) {
        this.usersListpage = usersListpage;
    }

    public List<Map<String, Object>> getListmapComm() {
        return listmapComm;
    }

    public void setListmapComm(List<Map<String, Object>> listmapComm) {
        this.listmapComm = listmapComm;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public Map<String, List<Map<String, Object>>> getUserListMap() {
        return userListMap;
    }

    public void setUserListMap(Map<String, List<Map<String, Object>>> userListMap) {
        this.userListMap = userListMap;
    }
}
